package cn.fcq.org.controller;

import cn.fcq.basic.anno.PreAuthorize;
import cn.fcq.basic.util.AjaxResult;
import cn.fcq.basic.util.PageList;
import cn.fcq.org.domain.Department;
import cn.fcq.org.query.DepartmentQuery;
import cn.fcq.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description = "部门的相关CRUD功能")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    // 查询一条数据
    @GetMapping("/{id}")
    @ApiOperation("部门的单个查询")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }

    // 查询所有
    @GetMapping
    @ApiOperation("部门的查询所有")
    public List<Department> queryAll(){
        return departmentService.queryAll();
    }

    // 新增或者修改
    @PutMapping
    @ApiOperation("部门的新增或者修改")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult
                    .me()
                    .setSuccess(false)
                    .setMessage("操作失误，请重试！");
        }

    }

    // 删除
    @DeleteMapping("/{id}")
    @ApiOperation("部门的删除")
    @PreAuthorize(name = "删除一条部门数据",value = "dept:deleteById")
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            departmentService.removeById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult
                    .me()
                    .setSuccess(false)
                    .setMessage("操作失败,请重试");
        }
    }
    /**
     * 批量删除
     *  如果前端传的是 数组,那么在后端可以使用 list 或者 数组 接收
     * @return
     */
    // 批量删除
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult
                    .me()
                    .setSuccess(false)
                    .setMessage("我们正在殴打程序员，请稍等！！");
        }

    }

    // 高级查询和分页
    @PostMapping
    @ApiOperation("高级查询")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);

    }
    @GetMapping("/tree")
    public List<Department> queryTree(){
        return departmentService.queryTree();
    }


}
